<template>
  <div class="departments">
    <el-card>
      <template #header>
        <div>组织架构</div>
      </template>
      <div class="tree">
        <TreeItem :item="topInfo"></TreeItem>

        <el-tree :data="list" :props="{ children: 'children' }">
          <template v-slot="{ data }">
            <TreeItem style="width:100%;" :item="data" @getDate="getDate"></TreeItem>
          </template>
        </el-tree>
      </div>
    </el-card>
    <!--  -->
    <DialogItem :initList="initList" @getDate="getDate" ref="dislogItem"></DialogItem>
  </div>
</template>

<script>
import TreeItem from './tree-item.vue'
import { companyDepartment } from '@/api/departments'
import DialogItem from './dialogItem.vue'
export default {
  components: {
    TreeItem,
    DialogItem
  },
  data () {
    return {
      topInfo: {
        name: '锤子',
        manager: '负责人',
        isTop: true,
        id: '' //确定当前点击项的pid
      },
      list: [],
      initList: [] //原始组织架构数据
    }
  },
  created () {
    this.getDate()
  },
  methods: {
    //调用接口并转树形结构
    async getDate () {
      const res = await companyDepartment()
      this.topInfo.name = res.data.companyName
      //加id，存储原始数据
      this.initList = res.data.depts //
      this.list = this.changeDate(res.data.depts, '')
      console.log('组织架构', res, this.list)
    },
    //重点
    changeDate (arr, str = '') {
      return arr.filter(item => {
        if (item.pid === str) {
          item.children = this.changeDate(arr, item.id)
          return true
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.departments {
  padding: 30px;
  .tree {
    width: 80%;
    margin: 0 auto;
  }
}
.el-tree {
  padding-top: 10px;
}
</style>
